import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/message")
public class MessageServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();// 解析 json对象

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理提交消息请求
        // 转为 java 对象
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        // 保存在内存中
        saveMessage(message);

        // 有了这样的声明，jQuery Ajax就会自动将其转为 js对象
//        resp.setContentType("application/json; charset=utf8");// 转成 json对象
//        resp.getWriter().write("{ \"ok\": true }");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取到消息列表
        //  使用 objectMapper将 java对象转为 Json 字符串
        List<Message> messages = loadMessage();
        resp.setContentType("application/json; charset=utf8");// 转成 json对象
        String respString = objectMapper.writeValueAsString(messages);
        resp.getWriter().write(respString);
    }

    private void saveMessage(Message message){
        Connection connection = null;
        PreparedStatement statement = null;
        // 将消息保存在数据库中
        try {
            connection = DBUtil.getConnection();
            String sql = "insert into message values(?, ?, ?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,message.from);
            statement.setString(2,message.to);
            statement.setString(3,message.content);

            // 执行语句
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }

    private List<Message> loadMessage(){
        // 获取消息列表
        List<Message> messages = new ArrayList<Message>();
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "select * from message";
            statement = connection.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()){
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.content = resultSet.getString("content");
                messages.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, statement, null);
        }
        return messages;
    }
}
class Message{
    public String from;
    public String to;
    public String content;
}